package com.example.xunua_weather;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.example.xunua_weather.Adapter.CityFragmentPagerAdapter;
import com.example.xunua_weather.Sqliteutils.DBManager;
import com.example.xunua_weather.fragment.CityWeatherFragment;

import java.util.ArrayList;
import java.util.List;


public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    RelativeLayout outLayout;
    ViewPager mainVp;
    List<Fragment>fragmentList;
    private List<String> list;
    ImageView addIv,moreIv;
    LinearLayout layout;  // 用于放置指示器的布局
    private List<ImageView>imgList;    //指示器所在的集合
    private CityFragmentPagerAdapter adapter;
    private SharedPreferences sp;
    private int bgNum;


    //读取本地sp文件 更换对应壁纸
    public void exchangeBg(){
        sp=getSharedPreferences("bg_sp",MODE_PRIVATE);
        bgNum = sp.getInt("bg", 2);
        switch (bgNum){
            case 0:
                outLayout.setBackgroundResource(R.mipmap.bg);
                break;
            case 1:
                outLayout.setBackgroundResource(R.mipmap.bg2);
                break;
            case 2:
                outLayout.setBackgroundResource(R.mipmap.bg3);
                break;
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        fragmentList=new ArrayList<>();
        imgList=new ArrayList<>();
        //从数据库中获取有哪些城市
         list= DBManager.queryAllCityName();
        //如果第一次加载数据，数据库当中不包含内容，list的长度将会为0，为了避免崩溃，手动添加一个默认地址
        if (list.size() == 0) {
            list.add("广州");
        }
        //因为可能接收搜索页面传来的数据，所以要接收一下
        try{
            Intent intent=getIntent();
            String city=intent.getStringExtra("city");
            if (!list.contains(city) && !TextUtils.isEmpty(city)) {
                list.add(city);
                mainVp.setCurrentItem(list.size()-1);
                changeRadio(list.size()-1);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        initPager();
        adapter=new CityFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);
        mainVp.setAdapter(adapter);

        initPoint();
        if (getIntent().getBooleanExtra("search",false)){
            mainVp.setCurrentItem(fragmentList.size()-1);
            changeRadio(fragmentList.size()-1);
        }
        setPagerrListener();
    }

    private void setPagerrListener() {
        //监听的方法
        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                changeRadio(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 小圆点的改变方法
     */
    private void changeRadio(int position){
        //小圆点的动态更换
        for (int i = 0; i < imgList.size(); i++) {
            imgList.get(i).setImageResource(R.mipmap.a1);
        }
        imgList.get(position).setImageResource(R.mipmap.a2);
    }
    private void initPoint() {
        //初始化指示器  那个小圆点
        for (int i = 0; i < fragmentList.size(); i++) {
            ImageView imageView=new ImageView(this);
            imageView.setImageResource(R.mipmap.a1);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp=(LinearLayout.LayoutParams)imageView.getLayoutParams();
            lp.setMargins(0,0,20,0);
            imgList.add(imageView);
            layout.addView(imageView);
        }
        imgList.get(0).setImageResource(R.mipmap.a2);
    }

    private  void init(){
        mainVp = findViewById(R.id.main_vp);
        addIv = findViewById(R.id.main_iv_add);
        moreIv = findViewById(R.id.main_iv_more);
        layout = findViewById(R.id.main_point_layout);
        outLayout = findViewById(R.id.main_outlayout);
        exchangeBg();//换壁纸的方法

        addIv.setOnClickListener(this);
        moreIv.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.main_iv_add:
                Intent intent = new Intent(this, CityManageActivity.class);
                startActivity(intent);
                break;
            case R.id.main_iv_more:
                Intent intent2 = new Intent(this, MoreActivity.class);
                startActivity(intent2);
                break;
        }
    }

    private  void initPager(){
        //给CityWeatherFragment传递activity中的城市和背景
        for (int i = 0; i < list.size(); i++) {
            CityWeatherFragment frag=new CityWeatherFragment();
            Bundle bundle=new Bundle();
            bundle.putString("city",list.get(i));
            bundle.putInt("bg",bgNum);
            frag.setArguments(bundle);
            fragmentList.add(frag);
        }
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //获取数据库中的城市
        List<String> citys=DBManager.queryAllCityName();
        if (citys.size() == 0) {
            citys.add("广州");
        }
        list.clear();
        list.addAll(citys);
        //剩余的城市创建fragment页面
        fragmentList.clear();
        initPager();
        //指示器数量减少，重新设置指示器
        imgList.clear();
        layout.removeAllViews();//移除指示器布局中所有元素
        initPoint();//更新指示器
        adapter.notifyDataSetChanged();//适配器刷新 提示数据源发生变化
//        mainVp.setCurrentItem(fragmentList.size()-1);//显示最后一个
        mainVp.setCurrentItem(0);//显示第一个
        changeRadio(0);

    }
}
